#
# $Header: mkinitramfs-ll/hooks/btrfs                    Exp $
# $Author: (c) 2011-6 tokiclover <tokiclover@gmail.com>  Exp $
# $License: 2-clause/new/simplified BSD                  Exp $
# $Version: 0.22.1 2019/01/02 12:33:03                   Exp $
#

[ -z "$bcache" ] && get_cmdline_option "btrfs"
[ -n "$btrfs" ] || exit

mount_btrfs() {
	echo $$ >/run/${0##*/}.pid
	local _bin _CHK _dev _DEV DEV name=btrfs
	$CHECK_ENV && debug -d check_bin btrfs
	debug MODPROBE btrfs

	debug -d test -n "$1" -a -n "$2" -a -n "$3"
	local _cut _env="$1" _grp="$2" _KEY _vol="$3"
	CUT "_CHK" "$rootfstype" ":" "2" "-s"
	[ $_grp -ge 2 ] && _cut=-s
	[ -n "$btrfs" ] && CUT "_DEV" "$btrfs" "," "$_grp" "$_cut"
	[ -n "$luks"  ] && CUT "_KEY" "$luks"  "," "$_grp" "$_cut"
	[ -n "$_DEV"  ] || return
	debug -d get_key "$_KEY"
	eval set -- $(echo "$_DEV" | sed 's/:/ /g')

	if ! btrfs filesystem show "${_vol#*=}" >$NULL 2>&1; then
		if yesno "$_DEV"; then
			error "No $_vol filesystem found"
			[ -n "$_CHK" ] || return
		fi
		if [ "$KEYMODE" != "none" ]; then
		for _dev in "$@"; do
			debug -d dmopen "$_dev" "_DEV"
			DEV="$_DEV $DEV"
		done
		fi
	fi
	if [ "$KEYMODE" = "none" ]; then
		for _dev in "$@"; do
			blk "$_dev" "_DEV"
			DEV="$_DEV $DEV"
		done
	fi
	debug -d btrfs device scan $DEV

	if [ -n "$_CHK" ]; then
		yesno "$_CHK" && _CHK=-d || _CHK=-e
		for _dev in $DEV; do
			debug $_CHK btrfs check --repair $_dev
		done
	fi
	debug -d mount -t btrfs ${rootflags:+-o} $rootflags $_vol $newroot
	echo "$_env=$_vol" >>/run/env
	rm -f /run/${0##*/}.pid
}

retval=0

if [ -n "$root"   ]; then
	debug mount_btrfs "ROOT" "1" "$root"
	retval="$?"
fi

exit "$retval"

#
# vim:fenc=utf-8:ft=sh:ci:pi:sts=0:sw=4:ts=4:
#
